//
//  FDOrderDetailWebSocketTool.m
//  FD
//
//  Created by xiaofang wang on 2019/1/5.
//  Copyright © 2019年 ZhiYuan Network. All rights reserved.
//

#import "FDOrderDetailWebSocketTool.h"
#import <SRWebSocket.h>
#import "FDDicJSONTool.h"

@interface FDOrderDetailWebSocketTool()<SRWebSocketDelegate>
/**socket*/
@property (nonatomic, strong) SRWebSocket *websocket;

@end

@implementation FDOrderDetailWebSocketTool

#pragma mark - 一 接口
- (void)setupWebSocketWithOrderId:(NSString *)orderId {
    //清空之前的
    self.websocket.delegate = nil;
    [self.websocket close];
    
    //创建request
    NSURLRequest *request = [FDHttpAPi rb_requestWithUserOrderId:orderId];
    self.websocket = [[SRWebSocket alloc] initWithURLRequest:request];
    
    self.websocket.delegate = self; //设置代理
    
    [self.websocket open]; //建立连接
}

- (void)closewebSocket {

    [self.websocket close];
}

#pragma mark - 二 SRWebSocketDelegate


// message will either be an NSString if the server is using text
// or NSData if the server is using binary.
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {

    FDLog(@"下载骑手坐标websocket收到消息");
    //转dic
    NSDictionary *responseDic = [FDDicJSONTool dicFromJSON:message];
    
    NSString *event = responseDic[@"event"];
    if ([event isEqualToString:@"RESPONSE_POSITION"]) { //下载骑手坐标
        NSDictionary *dataDic = responseDic[@"data"];
        
        //回调骑手坐标
        if (self.riderPositionBlock) {
            NSNumber *log = dataDic[@"longitude"];
            NSNumber *lat = dataDic[@"latitude"];
            self.riderPositionBlock(log, lat);
        }
        
    }else {
        FDLog(@"不是骑手坐标socket: %@",responseDic);
    }
}


//响应参数示例
/**
 {"event":"RESPONSE_POSITION","data":{"latitude":51.890282,"longitude":-8.538825},"describe":""}
 */


- (void)webSocketDidOpen:(SRWebSocket *)webSocket {

    FDLog(@"socket打开%s",__FUNCTION__);
}


- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
 
    FDLog(@"websocket连接失败:%@",error);
}


- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean {
    
    FDLog(@"socket关闭 code:%ld reason:%@ wasClean:%@",code,reason,(wasClean ? @"YES" : @"NO"));
}

@end
